package com.ticket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.entity.TicketPrice;
import com.ticket.entity.VenueSection;
import com.ticket.mapper.TicketPriceMapper;
import com.ticket.service.ISeatAllocationService;
import com.ticket.service.ITicketPriceService;
import com.ticket.service.IVenueSectionService;
import com.ticket.vo.TicketPriceVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TicketPriceServiceImpl extends ServiceImpl<TicketPriceMapper, TicketPrice> implements ITicketPriceService {

    @Autowired
    private IVenueSectionService venueSectionService;

    @Autowired
    private ISeatAllocationService seatAllocationService;

    @Override
    public List<TicketPriceVO> getTicketPricesByMatchId(Long matchId) {
        LambdaQueryWrapper<TicketPrice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketPrice::getMatchId, matchId);
        List<TicketPrice> prices = this.list(queryWrapper);

        if (prices.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取所有区域信息
        List<Long> sectionIds = prices.stream()
                .map(TicketPrice::getSectionId)
                .collect(Collectors.toList());

        List<VenueSection> sections = venueSectionService.listByIds(sectionIds);
        Map<Long, VenueSection> sectionMap = sections.stream()
                .collect(Collectors.toMap(VenueSection::getId, section -> section));

        // 转换为VO
        List<TicketPriceVO> voList = new ArrayList<>();
        for (TicketPrice price : prices) {
            TicketPriceVO vo = new TicketPriceVO();
            BeanUtils.copyProperties(price, vo);

            VenueSection section = sectionMap.get(price.getSectionId());
            if (section != null) {
                vo.setSectionName(section.getName());

                // 计算可用座位数
                Integer soldCount = seatAllocationService.getSoldSeatCount(matchId, price.getSectionId());
                vo.setAvailableSeats(section.getCapacity() - soldCount);
            }

            voList.add(vo);
        }

        return voList;
    }
}
